package com.agentfactory.teleoreactive.interpreter;

import com.agentfactory.logic.update.lang.IMPLIES;
import com.agentfactory.logic.update.lang.Predicate;
import com.agentfactory.platform.core.AgentCreationException;
import com.agentfactory.teleoreactive.compiler.CodeGeneratorVisitor;
import com.agentfactory.teleoreactive.compiler.SimpleNode;
import com.agentfactory.teleoreactive.compiler.TeleoReactiveParser;
import com.agentfactory.teleoreactive.interpreter.mentalstate.Action;
import com.agentfactory.teleoreactive.interpreter.mentalstate.Sensor;

public class ScriptBasedTeleoReactiveAgent extends TeleoReactiveAgent {

	public ScriptBasedTeleoReactiveAgent(String name) {
		super(name);
	}
	public void construct(String design) throws AgentCreationException {
		CodeGeneratorVisitor cgv = new CodeGeneratorVisitor();
		try {
			//TODO add included files
			TeleoReactiveParser parser = new TeleoReactiveParser(this.getClass().getClassLoader().getResourceAsStream(design));
			SimpleNode n = parser.Start();
			cgv.visit(n, null);
			
			if (!parser.errors.isEmpty()) {
				throw new RuntimeException("ERROR: Teleo-Reactive program does not compile: " + design);
			}
			
			for (Predicate belief: cgv.beliefs) {
				beliefs.addBelief(belief);
			}
			
			for (Predicate id: cgv.actions.keySet()) {
				Action action = (Action) Class.forName(cgv.actions.get(id)).newInstance();
				action.setId(id);
				action.setAgent(this);
				actionMap.put(Utilities.createSignature(id), action);
			}
			
			for (Predicate id: cgv.sensors.keySet()) {
				Sensor sensor = (Sensor) Class.forName(cgv.sensors.get(id)).newInstance();				
				sensor.setId(id);
				sensor.setAgent(this);
				sensorMap.put(Utilities.createSignature(id), sensor);
			}
			
			for (String key: cgv.programs.keySet()) {
				programs.put(key, cgv.programs.get(key));
			}
			for(IMPLIES i: cgv.resolutionRules){
				beliefs.addRule(i);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			throw new AgentCreationException(e.getMessage());
		}
	}
}
